package com.atguigu.gmall.feign;


import com.sun.org.apache.regexp.internal.RE;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

@Configuration
public class AppFeignConfig {

    /**
     * feign的拦截器
     * 作用：每次远程请求的时候，都会尝试给新的request带上请求头
     * @return
     */
    @Bean  //headerRequestInterceptor 请求拦截器
    RequestInterceptor headerRequestInterceptor(){
        RequestInterceptor interceptor = new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                //如果feign开启线程进行异步调用，这里会获取不到
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null){
                    HttpServletRequest request = requestAttributes.getRequest();
                    String userId = request.getHeader("userId");
                    String userTempId = request.getHeader("userTempId");
                    template.header("userId",userId);
                    template.header("userTempId",userTempId);
                }

            }
        };
        return interceptor;
    }
}
